<template>
  <div class="student-course">
    <!-- 单元列表 -->
    <el-card class="unit-list">
      <template #header>
        <div class="card-header">
          <span>教学单元列表</span>
        </div>
      </template>

      <el-table :data="unitList" style="width: 100%">
        <el-table-column prop="unit_title" label="单元名称" min-width="180"/>
        <el-table-column prop="courseName" label="所属课程" min-width="180"/>
        <el-table-column label="学习资料" width="280" align="center">
          <template #default="scope">
            <!-- 视频按钮 -->
            <el-button
                v-if="scope.row.video_path"
                type="primary"
                size="small"
                @click="watchVideo(scope.row)">
              <el-icon><VideoPlay /></el-icon>观看视频
            </el-button>
            <!-- 文档按钮 -->
            <el-button
                v-if="scope.row.doc_path"
                type="success"
                size="small"
                @click="downloadDoc(scope.row.doc_path)">
              <el-icon><Document /></el-icon>下载文档
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 视频播放对话框 -->
    <el-dialog
        v-model="videoDialogVisible"
        :title="currentUnit?.unit_title"
        width="70%"
        destroy-on-close
        :close-on-click-modal="false"
        :before-close="handleCloseDialog">
      <div class="video-container" v-if="currentUnit && videoUrl">
        <video
            ref="videoPlayer"
            controls
            class="video-player"
            @error="handleVideoError"
            @loadstart="handleVideoLoadStart"
            @loadeddata="handleVideoLoaded">
          <source :src="videoUrl" type="video/mp4">
          您的浏览器不支持 video 标签。
        </video>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "StudentCourse",
  data() {
    return {
      unitList: [], // 单元列表
      videoDialogVisible: false, // 视频对话框显示状态
      currentUnit: null, // 当前选中的单元
    }
  },
  created() {
    this.fetchUnitList()
  },
  methods: {
    // 获取学生所在班级的课程单元列表
    async fetchUnitList() {
      try {
        // 获取当前登录的学生信息
        const studentId = this.$store.getters.getUser.id;
        const response = await this.$axios.get('/course-learn-unit/student/units', {
          params: { studentId },
          headers: { Authorization: localStorage.getItem("token") }
        });

        if (response.data.code === 200) {
          this.unitList = response.data.data;
          console.log("133333333333333333333333333333")
          console.log(response.data.data)
          console.log("111111111111111111111111111111111")
        } else {
          ElMessage.error('获取单元列表失败');
        }
      } catch (error) {
        console.error('获取单元列表失败:', error);
        ElMessage.error('获取单元列表失败');
      }
    },

    // // 获取文件URL
    // getFileUrl(path) {
    //   // 返回完整的URL，包含token
    //   return `${path}?token=${localStorage.getItem("token")}`;
    // },

    // 观看视频
    watchVideo(unit) {
      console.log('正在打开视频:', unit);
      this.currentUnit = unit;
      // 添加时间戳防止缓存
      const timestamp = new Date().getTime();
      this.videoUrl = `${this.getFileUrl(unit.video_path)}?t=${timestamp}`;
      console.log('视频URL:', this.videoUrl);
      this.videoDialogVisible = true;
    },

// 获取文件URL - 用于视频播放
/*    getFileUrl(path) {
      if (!path) return '';
      // 从路径中提取需要的部分
      const parts = path.split('/');
      const unitId = parts[1].replace('unit_', '');
      const fileType = parts[2];
      const fileName = parts[3];
      return `/file/download/${unitId}/${fileType}/${fileName}`;
    },*/


    // 获取文件URL - 用于视频播放
    // 获取文件URL
    // 获取文件URL
    getFileUrl(path) {
      if (!path) {
        console.log('视频路径为空');
        return '';
      }
      const parts = path.split('/');
      const unitId = parts[1].replace('unit_', '');
      const fileType = parts[2];
      const fileName = parts[3];
      const url = `/file/download/${unitId}/${fileType}/${fileName}`;
      console.log('构建的URL:', url);
      return url;
    },

    // 处理视频错误
    handleVideoError(e) {
      console.error('视频加载错误:', e);
      console.error('错误详情:', {
        error: e.target.error,
        networkState: e.target.networkState,
        readyState: e.target.readyState
      });
      ElMessage.error('视频加载失败');
    },

    // 处理视频开始加载
    handleVideoLoadStart(e) {
      console.log('视频开始加载');
    },

    // 处理视频加载完成
    handleVideoLoaded(e) {
      console.log('视频加载完成');
    },

    // 处理对话框关闭
    handleCloseDialog(done) {
      if (this.$refs.videoPlayer) {
        this.$refs.videoPlayer.pause();
        this.$refs.videoPlayer.currentTime = 0;
      }
      this.videoUrl = null;
      done();
    },

    // 下载文档
    async downloadDoc(docPath) {
      try {
        console.log('开始下载文档，路径:', docPath);

        // 从路径中提取需要的部分
        const parts = docPath.split('/');
        const unitId = parts[1].replace('unit_', '');
        const fileType = parts[2];
        const fileName = parts[3];

        const downloadUrl = `/file/download/${unitId}/${fileType}/${fileName}`;
        console.log('下载URL:', downloadUrl);

        // 使用原生fetch API来处理下载
        const response = await fetch(downloadUrl, {
          method: 'GET',
          headers: {
            'Authorization': localStorage.getItem("token")
          }
        });

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        // 获取blob数据
        const blob = await response.blob();

        // 创建下载链接
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.style.display = 'none';
        link.href = url;
        link.download = fileName; // 设置下载文件名

        // 添加到文档并触发点击
        document.body.appendChild(link);
        link.click();

        // 清理
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);

        ElMessage.success('文档下载成功');
      } catch (error) {
        console.error('文档下载失败:', error);
        ElMessage.error('文档下载失败: ' + error.message);
      }
    },

    /* // 下载文档
     async downloadDoc(docPath) {
       try {
         // 使用axios发起请求，带上token
         const response = await this.$axios({
           method: 'get',
           url: `/file${docPath}`,
           responseType: 'blob', // 重要：指定响应类型为blob
           headers: {
             Authorization: localStorage.getItem("token")
           }
         });

         // 创建blob链接并下载
         const blob = new Blob([response.data]);
         const url = window.URL.createObjectURL(blob);
         const link = document.createElement('a');
         link.href = url;
         // 从路径中提取文件名
         const fileName = docPath.split('/').pop();
         link.setAttribute('download', fileName);
         document.body.appendChild(link);
         link.click();
         document.body.removeChild(link);
         window.URL.revokeObjectURL(url);
       } catch (error) {
         console.error('文档下载失败:', error);
         ElMessage.error('文档下载失败');
       }
     },*/

  }
}
</script>

<style scoped>
.video-container {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #000;
  padding: 20px 0;
}

.video-player {
  width: 100%;
  max-width: 800px;
  height: auto;
  box-shadow: 0 0 10px rgba(0,0,0,0.3);
}

:deep(.el-dialog__body) {
  padding: 0;
  background: #000;
}
.student-course {
  padding: 20px;
}

.unit-list {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.video-container {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.video-player {
  width: 100%;
  max-width: 800px;
  height: auto;
}

:deep(.el-button) {
  margin: 0 5px;
}
</style>






